package com.example.contactsbackup;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;

import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Gravity;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.view.Menu;

public class ContactsBackup extends Activity {

	public static final String TAG = "ADDRESSBOOK BACKUP";

	private ToXml toXml;
	 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts_backup);
        
        toXml = new ToXml(Environment.getExternalStorageDirectory().toString()
        	    + "/test.xml");
        populateContacts();
    }

    private void populateContacts() {
    	  try {
    	   toXml.initXML();

    	   ContentResolver cr = getContentResolver();

    	   Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
    	     null, null, null);

    	   if (cur.getCount() > 0) {

    	    while (cur.moveToNext()) {
    	     toXml.startContactElement();
    	     // ID AND NAME FROM CONTACTS CONTRACTS
    	     String id = cur.getString(cur
    	       .getColumnIndex(ContactsContract.Contacts._ID));
    	     String name = cur
    	       .getString(cur
    	         .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

    	     Log.i(TAG, "ID :" + id);
    	     Log.i(TAG, "NAME :" + name);
    	     toXml.createContactNameNode(name);

    	     // GET PHONE NUMBERS WITH QUERY STRING
    	     if (Integer
    	       .parseInt(cur.getString(cur
    	         .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
    	      Cursor pCur = cr
    	        .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
    	          null,
    	          ContactsContract.CommonDataKinds.Phone.CONTACT_ID
    	            + " = ?", new String[] { id },
    	          null);

    	      // WHILE WE HAVE CURSOR GET THE PHONE NUMERS
    	      while (pCur.moveToNext()) {
    	       // Do something with phones
    	       String phone = pCur
    	         .getString(pCur
    	           .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));

    	       String phoneType = pCur
    	         .getString(pCur
    	           .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));

    	       Log.i(TAG, "PHONE :" + phone);
    	       Log.i(TAG, "PHONE TYPE :" + phoneType);
    	       toXml.createPhoneNode(phone, phoneType);
    	      }
    	      pCur.close();
    	     }

    	     // WHILE WE HAVE CURSOR GET THE EMAIL
    	     Cursor emailCur = cr.query(
    	       ContactsContract.CommonDataKinds.Email.CONTENT_URI,
    	       null,
    	       ContactsContract.CommonDataKinds.Email.CONTACT_ID
    	         + " = ?", new String[] { id }, null);
    	     while (emailCur.moveToNext()) {
    	      // This would allow you get several email addresses
    	      // if the email addresses were stored in an array
    	      String email = emailCur
    	        .getString(emailCur
    	          .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
    	      String emailType = emailCur
    	        .getString(emailCur
    	          .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));

    	      Log.i(TAG, "EMAIL :" + email);
    	      Log.i(TAG, "EMAIL TYPE :" + emailType);
    	      toXml.createEmailNode(email, emailType);
    	     }
    	     emailCur.close();

    	     // FOR GETTTING ZIP & POSTAL
    	     String addrWhere = ContactsContract.Data.CONTACT_ID
    	       + " = ? AND " + ContactsContract.Data.MIMETYPE
    	       + " = ?";
    	     String[] addrWhereParams = new String[] {
    	       id,
    	       ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
    	     Cursor addrCur = cr.query(
    	       ContactsContract.Data.CONTENT_URI, null, addrWhere,
    	       addrWhereParams, null);

    	     while (addrCur.moveToNext()) {
    	      String poBox = addrCur
    	        .getString(addrCur
    	          .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
    	      String street = addrCur
    	        .getString(addrCur
    	          .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
    	      String city = addrCur
    	        .getString(addrCur
    	          .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
    	      String state = addrCur
    	        .getString(addrCur
    	          .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
    	      String postalCode = addrCur
    	        .getString(addrCur
    	          .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
    	      String country = addrCur
    	        .getString(addrCur
    	          .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
    	      String type = addrCur
    	        .getString(addrCur
    	          .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));

    	      Log.i(TAG, "POBOX :" + poBox);
    	      Log.i(TAG, "STREET :" + street);
    	      Log.i(TAG, "CITY :" + city);
    	      Log.i(TAG, "STATE :" + state);
    	      Log.i(TAG, "POSTALCODE :" + postalCode);
    	      Log.i(TAG, "COUNTRY :" + country);
    	      Log.i(TAG, "TYPE :" + type);
    	      if (street == null) {
    	       street = "";
    	      }
    	      if (city == null) {
    	       city = "";
    	      }
    	      if (state == null) {
    	       state = "";
    	      }
    	      if (postalCode == null) {
    	       postalCode = "";
    	      }
    	      if (country == null) {
    	       country = "";
    	      }
    	      toXml.createPostalAddressNode(type, street, city,
    	        state, postalCode, country);
    	     }
    	     addrCur.close();
    	     

    	     // Get Organization details..
    	     String noteWhere = ContactsContract.Data.CONTACT_ID
    	       + " = ? AND " + ContactsContract.Data.MIMETYPE
    	       + " = ?";
    	     String[] noteWhereParams = new String[] {
    	       id,
    	       ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE };
    	     Cursor noteCur = cr.query(
    	       ContactsContract.Data.CONTENT_URI, null, noteWhere,
    	       noteWhereParams, null);
    	     if (noteCur.moveToFirst()) {
    	      do {
    	       String company = noteCur
    	         .getString(noteCur
    	           .getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
    	       Log.i(TAG, "Org :" + company);

    	       String status = noteCur
    	         .getString(noteCur
    	           .getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
    	       Log.i(TAG, "Work :" + status);
    	       toXml.createOrganizationNode(company, status);
    	      } while (noteCur.moveToNext());

    	     }
    	     noteCur.close();

    	     // Instant messanger
    	     String imWhere = ContactsContract.Data.CONTACT_ID
    	       + " = ? AND " + ContactsContract.Data.MIMETYPE
    	       + " = ?";
    	     String[] imWhereParams = new String[] {
    	       id,
    	       ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE };
    	     Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,
    	       null, imWhere, imWhereParams, null);
    	     if (imCur.moveToFirst()) {
    	      String imName = imCur
    	        .getString(imCur
    	          .getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
    	      Log.i(TAG, "ImName :" + imName);
    	      String imType;
    	      imType = imCur
    	        .getString(imCur
    	          .getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA5));
    	      Log.i(TAG, "ImType :" + imType);
    	      toXml.createIMNode(imName, imType);
    	     }
    	     imCur.close();
    	     // Get Group Details

    	     String groupWhere = ContactsContract.Data.CONTACT_ID
    	       + " = ? AND " + ContactsContract.Data.MIMETYPE
    	       + " = ?";
    	     String[] groupWhereParams = new String[] {
    	       id,
    	       ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE };
    	     Cursor groupCur = cr.query(
    	       ContactsContract.Data.CONTENT_URI, null,
    	       groupWhere, groupWhereParams, null);
    	     if (groupCur.moveToFirst()) {
    	      do {
    	       String company = groupCur
    	         .getString(groupCur
    	           .getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.DATA1));
    	       Log.i(TAG, "Group :" + company);

    	       String status = groupCur
    	         .getString(groupCur
    	           .getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID));
    	       Log.i(TAG, "Type :" + status);

    	      } while (groupCur.moveToNext());

    	     }
    	     groupCur.close();
    	     toXml.endContactElement();
    	    }
    	   }
    	   toXml.closeXML();

    	  } catch (TransformerConfigurationException e) {
    	   // TODO Auto-generated catch block
    	   e.printStackTrace();
    	  } catch (ParserConfigurationException e) {
    	   // TODO Auto-generated catch block
    	   e.printStackTrace();
    	  } catch (SAXException e) {
    	   // TODO Auto-generated catch block
    	   e.printStackTrace();
    	  } catch (Exception e) {
    	   e.printStackTrace();
    	  }
    	 }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_contacts_backup, menu);
        return true;
    }
}
